import axios from "axios";
import router from "@/router";
import { Message } from "element-ui";
import store from "@/store";
import { uuid } from "./utils";
const request = axios.create({ timeout: 30 * 1000 });

// 添加请求拦截器
request.interceptors.request.use(
  async config => {
    // 在发送请求之前做些什么
    const visitor = localStorage.getItem("visitor");
    if (visitor) {
      config.headers.common["visitor-id"] = visitor;
    }
    config.headers.common["request-uuid"] = uuid();

    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
request.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    let response = {
      message: "网络请求失败，请稍后再试 :)"
    };
    if (error.response) {
      switch (error.response.status) {
        case 401:
          Message.error("登录过期,请重新登录");
          localStorage.removeItem("authority");
          store.commit("common/SET_STATE", {
            data: null,
            target: "authority"
          });
          if (router.currentRoute.fullPath.indexOf("redirect") !== -1) break; // 处理多次请求，redirect重复问题
          router.replace({
            path: "/home",
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
          break;
        case 500:
          Message.error("系统异常，请联系管理员 :)");
          break;
        case 502:
          Message.error("系统正在重启，请稍后再试 :)");
          break;
        case 503:
          Message.error("服务暂时不可用 :)");
          break;
        case 504:
          Message.error("系统繁忙，请稍后再试 :)");
          break;
        default:
          // Message.error(error.response.data.message);
          console.table(error.response.data);
      }
      response = {
        ...response,
        ...error.response.data,
        status: error.response.status
      };
    } else {
      Message.error(response.message);
    }
    return Promise.reject(response);
  }
);

// export const nhttp = {
//   async init() {
//     const visitor = localStorage.getItem("visitor");
//     if (!visitor) {
//       try {
//         const { data } = await request.post(api.visitorCreate);
//         localStorage.setItem("visitor", data.id);
//       } catch (e) {
//         console.error(e);
//       }
//     }
//   },
//   async get(...args) {
//     await this.init();
//     return request.get(...args);
//   },
//   async post(...args) {
//     await this.init();
//     return request.post(...args);
//   },
//   async put(...args) {
//     await this.init();
//     return request.put(...args);
//   },
//   async delete(...args) {
//     await this.init();
//     return request.delete(...args);
//   }
// };

export default request;
